package org.shopen.ai.puremvc.model.algo
{
	import mx.collections.ArrayCollection;
	
	import org.shopen.ai.puremvc.model.problem.IAction;
	import org.shopen.ai.puremvc.model.problem.IProblem;
	import org.shopen.ai.puremvc.model.problem.IState;

	public class SearchProblem implements ISearchProblem
	{
		protected var problem : IProblem;
		
		public function SearchProblem(problem : IProblem)
		{
			this.problem = problem;
		}

		public function get intialNode():ISearchNode
		{
			var result : ISearchNode = createSearchNode(problem.initialState);
			return result;
		}
		
		public function expand(node:ISearchNode):ArrayCollection
		{
			var result : ArrayCollection = new ArrayCollection();
			var stateFromNode : IState = node.state;
			
			for each (var action : IAction in problem.transitionModel.buildActions(stateFromNode))
			{
				var state : IState = problem.transitionModel.performAction(stateFromNode, action);
				var node : ISearchNode = createSearchNode(state, action, node);
				result.addItem(node);
			}
			return result;
		}
		
		public function isGoal(node:ISearchNode):Boolean
		{
			var stateFromNode : IState = node.state;
			var result : Boolean = problem.goalTest.checkState(stateFromNode);
			return result;
		}
		
		protected function createSearchNode(state : IState, action : IAction = null, parent : ISearchNode = null) : ISearchNode
		{
			var result : ISearchNode = null;
			var pathCost : Number = 0;
			if (parent != null && action != null)
			{
				pathCost = parent.pathCost;
				pathCost += problem.costFunction.getCost(parent.state, action);
			}
			result = new SearchNode(state, action, parent, pathCost);
			return result;
		}
	}
}